import { createDeck } from './Card.js';

export class GameEngine {
  constructor() {
    this.players = [];
    this.currentPlayerIndex = 0;
    this.currentRound = 1;
    this.roundCards = []; // 本轮出的牌
    this.collectedCards = {}; // 每个玩家收集的牌数
    this.gameStatus = 'waiting'; // waiting, playing, finished
    this.turnTimer = null;
    this.lastRoundWinner = null;
    this.waitingForCollection = false; // 等待收牌
    this.roundWinner = null; // 本轮赢家
    this.firstPlayer = null; // 首发玩家（第一局随机选择）
    this.isFirstRound = true; // 是否为第一轮

    // 扣了相关状态
    this.kouLeStatus = {
      isActive: false,           // 是否处于扣了决策中
      initiator: null,           // 发起扣了的玩家
      initiatorPlayer: null,     // 发起扣了的玩家对象
      decisions: {},             // 各玩家的决策 {playerId: 'kou'/'xuan'}
      xuanPlayers: [],          // 选择"宣"的玩家列表
      riskMultiplier: 2         // 风险倍数
    };

    // 游戏结算时的额外支付
    this.riskPayments = [];     // 风险支付记录
  }

  // 异步初始化游戏
  async initGameAsync(players) {
    this.players = players;
    // 随机决定谁先出牌（0, 1, 2中随机选择）
    this.currentPlayerIndex = Math.floor(Math.random() * 3);
    this.firstPlayer = this.players[this.currentPlayerIndex]; // 记录首发玩家
    this.isFirstRound = true; // 标记为第一轮
    this.currentRound = 1;
    this.roundCards = [];
    this.collectedCards = {};
    this.gameStatus = 'playing';

    // 初始化收牌数
    players.forEach(player => {
      this.collectedCards[player.id] = 0;
    });

    // 给玩家分配固定的座位索引
    players.forEach((player, index) => {
      player.seatIndex = index;
    });

    // 异步发牌
    await this.dealCardsAsync();

    // 检查无相情况
    const wuxiangResult = this.checkWuxiang();
    if (wuxiangResult.hasWuxiang) {
      return { needRedeal: true, wuxiangPlayer: wuxiangResult.player };
    }

    return { needRedeal: false };
  }

  // 检查无相情况
  checkWuxiang() {
    // 关键牌型：红相、黑相、红尔、黑尔
    const keyCardNames = ['红相', '黑相', '红尔', '黑尔'];

    for (let player of this.players) {
      const hasKeyCard = player.cards.some(card =>
        keyCardNames.includes(card.displayName)
      );

      if (!hasKeyCard) {
        return {
          hasWuxiang: true,
          player: player,
          missingCards: keyCardNames
        };
      }
    }

    return { hasWuxiang: false };
  }

  // 异步发牌
  async dealCardsAsync() {
    const deck = createDeck();

    // 异步洗牌
    await this.shuffleDeckAsync(deck);

    // 清空玩家手牌
    this.players.forEach(player => {
      player.cards = [];
    });

    // 分批发牌，避免阻塞
    for (let i = 0; i < 24; i += 3) {
      // 每次发3张牌（一轮）
      for (let j = 0; j < 3 && i + j < 24; j++) {
        const playerIndex = (i + j) % 3;
        this.players[playerIndex].cards.push(deck[i + j]);
      }

      // 每发一轮牌后短暂暂停，让UI有机会更新
      if (i > 0 && i % 9 === 0) {
        await new Promise(resolve => setTimeout(resolve, 50));
      }
    }

    // 异步排序手牌
    await this.sortPlayerCardsAsync();
  }

  // 异步洗牌
  async shuffleDeckAsync(deck) {
    // 使用Fisher-Yates洗牌算法，分批处理
    const batchSize = 10;

    for (let i = deck.length - 1; i > 0; i -= batchSize) {
      // 处理一批
      const start = Math.max(0, i - batchSize + 1);
      for (let j = i; j >= start; j--) {
        const randomIndex = Math.floor(Math.random() * (j + 1));
        [deck[j], deck[randomIndex]] = [deck[randomIndex], deck[j]];
      }

      // 每处理一批后短暂暂停
      if (i > batchSize) {
        await new Promise(resolve => setTimeout(resolve, 10));
      }
    }
  }

  // 异步排序玩家手牌
  async sortPlayerCardsAsync() {
    for (let i = 0; i < this.players.length; i++) {
      this.players[i].cards = this.smartSortCards(this.players[i].cards);

      // 每排序一个玩家后短暂暂停
      if (i < this.players.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 30));
      }
    }
  }

  // 智能排序卡牌 - 按牌力从大到小排序，同时将对子放在一起
  smartSortCards(cards) {
    // 先按牌力从大到小排序
    const sorted = [...cards].sort((a, b) => b.power - a.power);

    // 然后调整顺序，确保对子相邻
    const result = [];
    const used = new Set();

    for (let i = 0; i < sorted.length; i++) {
      if (used.has(sorted[i].id)) continue;

      result.push(sorted[i]);
      used.add(sorted[i].id);

      // 查找是否有能与当前牌配对的牌
      for (let j = i + 1; j < sorted.length; j++) {
        if (used.has(sorted[j].id)) continue;

        if (sorted[i].canPairWith(sorted[j])) {
          // 找到对子，立即将配对的牌放在后面
          result.push(sorted[j]);
          used.add(sorted[j].id);
          break;
        }
      }
    }

    // 调试：打印排序信息
    console.log('排序前的牌:', cards.map(c => `${c.displayName}(${c.power})`).join(', '));
    console.log('排序后的牌:', result.map(c => `${c.displayName}(${c.power})`).join(', '));

    return result;
  }

  // 发牌
  dealCards() {
    const deck = createDeck();

    // 洗牌
    for (let i = deck.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [deck[i], deck[j]] = [deck[j], deck[i]];
    }

    // 清空玩家手牌
    this.players.forEach(player => {
      player.cards = [];
    });

    // 轮流发牌，每人8张
    for (let i = 0; i < 24; i++) {
      const playerIndex = i % 3;
      this.players[playerIndex].cards.push(deck[i]);
    }

    // 对手牌排序
    this.players.forEach(player => {
      player.cards = this.smartSortCards(player.cards);
    });
  }

  // 获取当前玩家
  getCurrentPlayer() {
    return this.players[this.currentPlayerIndex];
  }

  // 验证出牌是否合法
  validatePlay(playerId, cards) {
    const player = this.players.find(p => p.id === playerId);
    if (!player) {
      return { valid: false, message: '玩家不存在' };
    }

    // 检查是否轮到该玩家
    if (this.players[this.currentPlayerIndex].id !== playerId) {
      return { valid: false, message: '不是你的回合' };
    }

    // 检查玩家是否拥有这些牌
    const hasAllCards = cards.every(card =>
      player.cards.some(c => c.id === card.id)
    );
    if (!hasAllCards) {
      return { valid: false, message: '你没有这些牌' };
    }

    // 检查出牌数量
    if (cards.length < 1) {
      return { valid: false, message: '至少要出一张牌' };
    }

    // 检查是否是有效的组合
    if (cards.length === 2) {
      // 检查对子是否合法
      if (!cards[0].canPairWith(cards[1])) {
        return { valid: false, message: '这两张牌不能组成对子' };
      }
    } else if (cards.length > 2) {
      // 多张牌，检查是否都是同色曲曲
      const ququRanks = ['J', 'Q', 'K'];
      const allQuqu = cards.every(c => ququRanks.includes(c.rank));
      if (!allQuqu) {
        return { valid: false, message: '只有同色曲曲可以一起出多张' };
      }

      // 检查颜色是否一致
      const redSuits = ['hearts', 'diamonds'];
      const firstIsRed = redSuits.includes(cards[0].suit);
      const allSameColor = cards.every(c => {
        const isRed = redSuits.includes(c.suit);
        return isRed === firstIsRed;
      });

      if (!allSameColor) {
        return { valid: false, message: '多张曲曲必须颜色相同' };
      }
    }

    // 如果本轮已有出牌，检查出牌规则
    if (this.roundCards.length > 0) {
      const firstPlay = this.roundCards[0];

      // 检查出牌数量是否一致
      if (cards.length !== firstPlay.cards.length) {
        return { valid: false, message: `必须出${firstPlay.cards.length}张牌` };
      }

      // 获取当前最大牌力
      const currentMaxPower = Math.max(...this.roundCards
        .filter(p => !p.passed)
        .map(p => p.power));

      // 计算出牌的牌力
      const playPower = this.calculatePlayPower(cards);

      // 特殊规则：大小王对和红尔对不分胜负
      if (playPower === currentMaxPower && playPower === 125) {
        // 如果当前桌面是大小王对或红尔对，且要出的也是大小王对或红尔对，不能出
        return { valid: false, message: '大小王对和红尔对不分胜负，不能出牌' };
      }

      // 检查是否能打过当前牌
      if (playPower <= currentMaxPower) {
        return { valid: false, message: '出的牌必须大于桌面上的牌' };
      }
    }

    return { valid: true };
  }

  // 查找所有可能的出牌组合
  findPossiblePlays(player, requiredCount) {
    const possiblePlays = [];

    if (requiredCount === 1) {
      // 单牌，每张都可以出
      player.cards.forEach(card => {
        possiblePlays.push([card]);
      });
    } else if (requiredCount === 2) {
      // 对子
      for (let i = 0; i < player.cards.length - 1; i++) {
        for (let j = i + 1; j < player.cards.length; j++) {
          if (player.cards[i].canPairWith(player.cards[j])) {
            possiblePlays.push([player.cards[i], player.cards[j]]);
          }
        }
      }
    } else {
      // 多张（曲曲）
      const ququRanks = ['J', 'Q', 'K'];
      const redQu = player.cards.filter(c => ququRanks.includes(c.rank) && ['hearts', 'diamonds'].includes(c.suit));
      const blackQu = player.cards.filter(c => ququRanks.includes(c.rank) && ['spades', 'clubs'].includes(c.suit));

      // 找出所有可能的组合
      if (redQu.length >= requiredCount) {
        this.getCombinations(redQu, requiredCount).forEach(combo => {
          possiblePlays.push(combo);
        });
      }
      if (blackQu.length >= requiredCount) {
        this.getCombinations(blackQu, requiredCount).forEach(combo => {
          possiblePlays.push(combo);
        });
      }
    }

    return possiblePlays;
  }

  // 获取组合
  getCombinations(arr, size) {
    const result = [];

    function combine(start, combo) {
      if (combo.length === size) {
        result.push([...combo]);
        return;
      }

      for (let i = start; i < arr.length; i++) {
        combo.push(arr[i]);
        combine(i + 1, combo);
        combo.pop();
      }
    }

    combine(0, []);
    return result;
  }

  // 玩家出牌
  playCards(playerId, cards) {
    const validation = this.validatePlay(playerId, cards);
    if (!validation.valid) {
      return validation;
    }

    const player = this.players.find(p => p.id === playerId);

    // 从手牌中移除出的牌
    cards.forEach(card => {
      const index = player.cards.findIndex(c => c.id === card.id);
      if (index !== -1) {
        player.cards.splice(index, 1);
      }
    });

    // 记录本轮出牌
    this.roundCards.push({
      player: player,
      cards: cards,
      power: this.calculatePlayPower(cards)
    });

    // 下一个玩家
    this.nextTurn();

    return { valid: true };
  }

  // 玩家扣牌（不跟）
  pass(playerId, cardsToDiscard = null) {
    const player = this.players.find(p => p.id === playerId);
    if (!player) {
      return { valid: false, message: '玩家不存在' };
    }

    if (this.players[this.currentPlayerIndex].id !== playerId) {
      return { valid: false, message: '不是你的回合' };
    }

    // 第一个出牌的人不能扣牌
    if (this.roundCards.length === 0) {
      return { valid: false, message: '第一个出牌的人不能扣牌' };
    }

    // 检查是否有可以出的牌（强制出牌规则）
    const firstPlay = this.roundCards[0];
    const requiredCount = firstPlay.cards.length;
    const currentMaxPower = Math.max(...this.roundCards
      .filter(p => !p.passed)
      .map(p => p.power));

    // 查找所有可能的出牌组合
    const possiblePlays = this.findPossiblePlays(player, requiredCount);

    // 检查是否有能打过当前牌的组合
    const hasValidPlay = possiblePlays.some(play => {
      const power = this.calculatePlayPower(play);
      // 特殊规则：大小王对和红尔对不分胜负，相等时不能出
      if (power === currentMaxPower && power === 125) {
        return false;
      }
      return power > currentMaxPower;
    });

    if (hasValidPlay) {
      return { valid: false, message: '你有可以出的牌，不能扣牌' };
    }

    // 扣牌时需要从手牌中移除相应数量的牌
    let cardsToRemove = [];
    if (cardsToDiscard && cardsToDiscard.length > 0) {
      // 使用用户选择的牌
      cardsToRemove = cardsToDiscard.slice();
      // 从玩家手牌中移除这些牌
      cardsToRemove.forEach(card => {
        const index = player.cards.findIndex(c => c.id === card.id);
        if (index !== -1) {
          player.cards.splice(index, 1);
        }
      });
    } else {
      // 如果没有指定扣牌，自动选择最小的牌（向后兼容AI）
      for (let i = 0; i < requiredCount && player.cards.length > 0; i++) {
        // 移除最小的牌（从最后开始，因为已排序）
        const cardToRemove = player.cards.pop();
        if (cardToRemove) {
          cardsToRemove.push(cardToRemove);
        }
      }
    }

    // 记录扣牌
    this.roundCards.push({
      player: player,
      cards: [],
      power: 0,
      passed: true,
      discardedCards: cardsToRemove // 记录实际扣掉的牌
    });

    // 下一个玩家
    this.nextTurn();

    return { valid: true };
  }

  // 计算出牌的牌力
  calculatePlayPower(cards) {
    if (cards.length === 0) return 0;

    // 单牌直接返回牌力
    if (cards.length === 1) {
      return cards[0].power;
    }

    // 对子，牌力加100以区分单牌
    if (cards.length === 2) {
      // 检查是否是大小王对
      const isDaXiaoWangPair = cards.every(c => c.rank === 'joker') &&
                              cards[0].displayName !== cards[1].displayName;

      // 检查是否是红尔对
      const isRedErPair = cards.every(c => c.displayName === '红尔');

      if (isDaXiaoWangPair) {
        // 大小王对特殊牌力：125（和红尔对相等，表示不分胜负）
        return 125;
      } else if (isRedErPair) {
        // 红尔对特殊牌力：125（和大小王对相等，表示不分胜负）
        return 125;
      } else {
        return cards[0].power + 100;
      }
    }

    // 三张或更多（曲曲），牌力加200
    if (cards.length >= 3) {
      // 使用最大的牌力值作为基准
      const maxPower = Math.max(...cards.map(c => c.power));
      return maxPower + 200;
    }

    return 0;
  }

  // 下一个玩家
  nextTurn() {
    // 检查本轮是否结束（所有人都出牌或扣牌了）
    if (this.roundCards.length === 3) {
      // 标记等待收牌
      this.waitingForCollection = true;
      this.calculateRoundWinner();
      return;
    }

    // 顺时针下一个玩家
    this.currentPlayerIndex = (this.currentPlayerIndex + 1) % 3;
  }

  // 计算本轮赢家
  calculateRoundWinner() {
    let winner = null;
    let maxPower = -1;

    this.roundCards.forEach(play => {
      if (!play.passed && play.power > maxPower) {
        maxPower = play.power;
        winner = play.player;
      }
    });

    this.roundWinner = winner;
  }

  // 收牌
  collectCards() {
    if (!this.waitingForCollection) return;

    if (this.roundWinner) {
      // 计算收牌数量 - 每个玩家出牌或扣牌的数量 × 3
      // 第一个出牌决定了本轮每人应该出几张
      const cardsPerPlayer = this.roundCards[0].cards.length;

      // 收牌数 = 每人应出牌数 × 3人
      const cardsToCollect = cardsPerPlayer * 3;
      this.collectedCards[this.roundWinner.id] += cardsToCollect;

      // 设置下轮首家
      this.currentPlayerIndex = this.players.findIndex(p => p.id === this.roundWinner.id);
      this.lastRoundWinner = this.roundWinner;
    }

    // 清空本轮记录
    this.roundCards = [];
    this.waitingForCollection = false;
    this.roundWinner = null;
    this.currentRound++;

    // 第一轮结束后，标记为非首轮
    if (this.isFirstRound) {
      this.isFirstRound = false;
    }

    // 检查游戏是否结束
    if (this.isGameOver()) {
      this.endGame();
    }
  }

  // 结束本轮
  endRound() {
    // 找出本轮赢家
    let winner = null;
    let maxPower = -1;

    this.roundCards.forEach(play => {
      if (!play.passed && play.power > maxPower) {
        maxPower = play.power;
        winner = play.player;
      }
    });

    if (winner) {
      // 计算收牌数量
      const cardCount = this.calculateCollectedCards();
      this.collectedCards[winner.id] += cardCount;

      // 设置下轮首家
      this.currentPlayerIndex = this.players.findIndex(p => p.id === winner.id);
      this.lastRoundWinner = winner;
    }

    // 清空本轮记录
    this.roundCards = [];
    this.currentRound++;

    // 检查游戏是否结束
    if (this.isGameOver()) {
      this.endGame();
    }
  }

  // 计算本轮收牌数量
  calculateCollectedCards() {
    const actualCards = this.roundCards.reduce((sum, play) => {
      if (!play.passed) {
        return sum + play.cards.length;
      }
      return sum;
    }, 0);

    // 返回实际出牌数
    return actualCards;
  }

  // 检查游戏是否结束
  isGameOver() {
    // 任意玩家手牌打完即结束
    return this.players.some(player => player.cards.length === 0);
  }

  // 结束游戏
  endGame() {
    this.gameStatus = 'finished';

    // 计算最终结果
    const results = this.calculateGameResults();
    return results;
  }

  // 计算游戏结果
  calculateGameResults() {
    const results = [];

    this.players.forEach(player => {
      const collected = this.collectedCards[player.id] || 0;
      let level = '不够';
      let coins = 0;

      if (collected >= 18) {
        level = '此了';
        coins = 3;
      } else if (collected >= 15) {
        level = '五了';
        coins = 2;
      } else if (collected >= 9) {
        level = '刚够';
        coins = 1;
      }

      results.push({
        player: player,
        collected: collected,
        level: level,
        coins: coins
      });
    });

    // 计算支付关系
    const payments = this.calculatePayments(results);

    return {
      results: results,
      payments: payments
    };
  }

  // 计算支付关系
  calculatePayments(results) {
    const losers = results.filter(r => r.level === '不够');
    const winners = results.filter(r => r.level !== '不够');
    const payments = [];

    // 基础支付
    losers.forEach(loser => {
      winners.forEach(winner => {
        payments.push({
          from: loser.player.id,
          to: winner.player.id,
          amount: winner.coins,
          fromName: loser.player.name,
          toName: winner.player.name,
          type: 'base'
        });
      });
    });

    // 处理"宣"的风险支付
    if (this.kouLeStatus.xuanPlayers && this.kouLeStatus.xuanPlayers.length > 0) {
      const initiatorId = this.kouLeStatus.initiator;
      const initiatorResult = results.find(r => r.player.id === initiatorId);

      // 只有当发起"扣了"的玩家赢了，才需要处理风险支付
      if (initiatorResult && initiatorResult.level !== '不够') {
        this.kouLeStatus.xuanPlayers.forEach(xuanPlayerId => {
          const xuanResult = results.find(r => r.player.id === xuanPlayerId);

          // 如果"宣"的玩家输了
          if (xuanResult && xuanResult.level === '不够') {
            // 需要额外支付给发起"扣了"的玩家
            const riskAmount = initiatorResult.coins * this.kouLeStatus.riskMultiplier;
            payments.push({
              from: xuanPlayerId,
              to: initiatorId,
              amount: riskAmount,
              fromName: xuanResult.player.name,
              toName: initiatorResult.player.name,
              type: 'risk',
              riskMultiplier: this.kouLeStatus.riskMultiplier
            });
          }
        });
      }
    }

    return payments;
  }

  // AI玩家自动出牌
  makeAIMove(playerId) {
    const player = this.players.find(p => p.id === playerId);
    if (!player || !player.isAI) return;

    // 高级AI策略：优先考虑多张牌组合和对子
    if (this.roundCards.length === 0) {
      // 第一个出牌，使用策略选择
      // 检查是否应该发起扣了
      const shouldInitiateKouLe = this.shouldAIInitiateKouLe(player);
      if (shouldInitiateKouLe) {
        return this.initiateKouLe(playerId);
      }

      const bestPlay = this.selectBestFirstPlay(player);
      return this.playCards(playerId, bestPlay);
    } else {
      // 跟牌，优先选择对子和多张曲曲
      const firstPlay = this.roundCards[0];
      const requiredCount = firstPlay.cards.length;
      const currentPower = Math.max(...this.roundCards.filter(p => !p.passed).map(p => p.power));

      // 查找所有可能的出牌组合
      const possiblePlays = this.findPossiblePlays(player, requiredCount);

      // 找出能赢的组合
      const winningPlays = possiblePlays.filter(play => {
        const power = this.calculatePlayPower(play);
        // 特殊规则：大小王对和红尔对不分胜负，相等时不能出
        if (power === currentPower && power === 125) {
          return false;
        }
        return power > currentPower;
      });

      if (winningPlays.length > 0) {
        // 使用智能策略选择最佳出牌
        const bestPlay = this.selectBestAIPlay(player, winningPlays, currentPower);
        return this.playCards(playerId, bestPlay);
      } else {
        // 没有能赢的牌，必须扣牌
        return this.pass(playerId);
      }
    }
  }

  // 智能选择单张牌 - 避免拆散对子
  selectSmartSingleCard(player, preferredPowerRange = 'min') {
    // 找出所有能组成对子的牌
    const pairCards = new Set();
    for (let i = 0; i < player.cards.length - 1; i++) {
      for (let j = i + 1; j < player.cards.length; j++) {
        if (player.cards[i].canPairWith(player.cards[j])) {
          pairCards.add(player.cards[i].id);
          pairCards.add(player.cards[j].id);
        }
      }
    }

    // 找出不会拆散对子的单牌
    const safeCards = player.cards.filter(card => !pairCards.has(card.id));

    if (safeCards.length > 0) {
      // 根据策略选择合适的安全单牌
      if (preferredPowerRange === 'min') {
        return safeCards[safeCards.length - 1]; // 最小的安全牌
      } else if (preferredPowerRange === 'mid') {
        const midIndex = Math.floor(safeCards.length * 0.5);
        return safeCards[midIndex]; // 中等的安全牌
      }
    }

    // 如果没有安全牌，选择牌力最小且只出现一次的牌
    const cardCounts = new Map();
    player.cards.forEach(card => {
      const key = `${card.rank}_${card.displayName}`;
      cardCounts.set(key, (cardCounts.get(key) || 0) + 1);
    });

    // 优先选择只有一张的牌（不会影响对子）
    for (let i = player.cards.length - 1; i >= 0; i--) {
      const card = player.cards[i];
      const key = `${card.rank}_${card.displayName}`;
      if (cardCounts.get(key) === 1) {
        return card;
      }
    }

    // 实在没办法，选择最小的牌
    return player.cards[player.cards.length - 1];
  }

  // AI选择最佳首发牌
  selectBestFirstPlay(player) {
    // 计算剩余手牌轮数（估算能赢几轮）
    const remainingCards = player.cards.length;
    const currentCollected = this.collectedCards[player.id] || 0;
    const needMoreCards = currentCollected < 9;
    const urgentNeed = currentCollected < 6;

    // 评估手牌整体强度
    const averagePower = player.cards.reduce((sum, card) => sum + card.power, 0) / player.cards.length;
    const hasStrongCards = player.cards.some(card => card.power >= 22); // 有红相以上
    const isWeakHand = averagePower < 18; // 平均牌力较弱

    // 策略1：如果有三张红曲曲，必出（基本无敌）
    const redQuqu = player.cards.filter(c =>
      ['J', 'Q', 'K'].includes(c.rank) && ['hearts', 'diamonds'].includes(c.suit)
    );
    if (redQuqu.length >= 3) {
      return redQuqu.slice(0, 3);
    }

    // 策略2：如果有三张黑曲曲，更积极地出
    const blackQuqu = player.cards.filter(c =>
      ['J', 'Q', 'K'].includes(c.rank) && ['spades', 'clubs'].includes(c.suit)
    );
    if (blackQuqu.length >= 3) {
      // 需要收牌、手牌弱、或者手牌不多时，积极出3张
      if (needMoreCards || isWeakHand || remainingCards <= 6) {
        return blackQuqu.slice(0, 3);
      }
      // 否则90%概率出（比之前更积极）
      if (Math.random() > 0.1) {
        return blackQuqu.slice(0, 3);
      }
    }

    // 策略3：对子策略 - 更积极的收牌导向
    const pairs = this.findAllPairs(player);
    if (pairs.length > 0) {
      // 按牌力排序，选择合适的对子
      pairs.sort((a, b) => this.calculatePlayPower(b) - this.calculatePlayPower(a));

      const topPair = pairs[0];
      const topPairPower = this.calculatePlayPower(topPair);

      // 大小王对或红尔对 - 几乎必出的超强对子
      if (topPairPower >= 125) {
        // 急需收牌时必出，否则95%概率出
        if (urgentNeed || needMoreCards || Math.random() > 0.05) {
          return topPair;
        }
      }

      // 红相对、黑相对等强对子
      if (topPairPower >= 121) { // 红相对+100 = 122
        // 需要收牌时90%概率出
        if (needMoreCards && Math.random() > 0.1) {
          return topPair;
        }
        // 手牌弱时也要积极出
        if (isWeakHand && Math.random() > 0.2) {
          return topPair;
        }
      }

      // 其他对子 - 根据整体策略决定
      if (topPairPower >= 118) { // 红马对以上
        // 急需收牌或手牌弱时，75%概率出
        if ((urgentNeed || isWeakHand) && Math.random() > 0.25) {
          return topPair;
        }
        // 普通需要收牌时，60%概率出
        if (needMoreCards && Math.random() > 0.4) {
          return topPair;
        }
      }

      // 普通对子，保守策略
      if (needMoreCards && Math.random() > 0.6) { // 40%概率
        return topPair;
      }
    }

    // 策略4：单张牌策略 - 根据整体情况选择
    if (currentCollected >= 12) {
      // 已经收很多牌，非常保守
      return [this.selectSmartSingleCard(player, 'min')];
    } else if (currentCollected >= 9) {
      // 收够牌了，但可以适度积极确保胜利
      return [this.selectSmartSingleCard(player, 'min')];
    } else if (isWeakHand || urgentNeed) {
      // 手牌弱或急需收牌，出中等偏强的单牌
      const selectedCard = this.selectSmartSingleCard(player, 'mid');
      // 如果选中的牌太弱，尝试选择更强的
      if (selectedCard.power < 20 && hasStrongCards) {
        // 找一张不会破坏对子的强单牌
        const strongSafeCard = player.cards.find(card =>
          card.power >= 22 && !this.wouldBreakPair(player, card)
        );
        if (strongSafeCard) {
          return [strongSafeCard];
        }
      }
      return [selectedCard];
    } else {
      // 普通情况，出中等牌力单牌
      return [this.selectSmartSingleCard(player, 'mid')];
    }
  }

  // 检查出某张牌是否会破坏对子组合
  wouldBreakPair(player, card) {
    return player.cards.some(otherCard =>
      otherCard.id !== card.id && card.canPairWith(otherCard)
    );
  }

  // AI选择最佳跟牌策略
  selectBestAIPlay(player, winningPlays, currentPower) {
    const currentCollected = this.collectedCards[player.id] || 0;
    const remainingCards = player.cards.length;

    // 更精确的收牌需求评估
    const needMoreCards = currentCollected < 9;
    const urgentNeed = currentCollected < 6; // 急需收牌
    const canBeConservative = currentCollected >= 12; // 可以保守

    // 按牌力排序（从小到大）
    winningPlays.sort((a, b) => {
      const powerA = this.calculatePlayPower(a);
      const powerB = this.calculatePlayPower(b);
      return powerA - powerB;
    });

    // 策略1：如果有三张红曲曲且急需收牌，必出
    const hasRedThree = winningPlays.find(play =>
      play.length >= 3 &&
      play.every(c => ['J', 'Q', 'K'].includes(c.rank) && ['hearts', 'diamonds'].includes(c.suit))
    );
    if (hasRedThree && (urgentNeed || (needMoreCards && remainingCards <= 4))) {
      return hasRedThree;
    }

    // 策略2：如果有黑曲曲3张且非常需要收牌，考虑出
    const hasBlackThree = winningPlays.find(play =>
      play.length >= 3 &&
      play.every(c => ['J', 'Q', 'K'].includes(c.rank) && ['spades', 'clubs'].includes(c.suit))
    );
    if (hasBlackThree && urgentNeed) {
      return hasBlackThree;
    }

    // 策略3：强对子策略 - 根据收牌需求决定
    const strongPairs = winningPlays.filter(play => {
      if (play.length !== 2) return false;
      const power = this.calculatePlayPower(play);
      return power >= 125; // 大小王对或红尔对
    });

    if (strongPairs.length > 0) {
      const strongPair = strongPairs[0];
      const pairPower = this.calculatePlayPower(strongPair);

      // 如果急需收牌或对手牌力很高，出强对子
      if (urgentNeed || currentPower >= 115) {
        return strongPair;
      }

      // 如果已经收够牌且牌力差距很大，保留强对子
      if (canBeConservative && pairPower - currentPower > 8) {
        // 继续寻找更小的牌
      } else if (needMoreCards) {
        return strongPair;
      }
    }

    // 策略4：智能选择最合适的牌
    const selectedPlay = winningPlays[0]; // 最小能赢的牌
    const selectedPower = this.calculatePlayPower(selectedPlay);
    const powerGap = selectedPower - currentPower;

    // 如果是单张牌，尽量避免拆散对子
    if (selectedPlay.length === 1) {
      // 查找所有单张牌中能保护对子组合的选择
      const singleWinningPlays = winningPlays.filter(play => play.length === 1);

      if (singleWinningPlays.length > 1) {
        // 找出不会拆散对子的安全单牌
        const pairCards = new Set();
        for (let i = 0; i < player.cards.length - 1; i++) {
          for (let j = i + 1; j < player.cards.length; j++) {
            if (player.cards[i].canPairWith(player.cards[j])) {
              pairCards.add(player.cards[i].id);
              pairCards.add(player.cards[j].id);
            }
          }
        }

        // 优先选择不会破坏对子的牌
        const safeSinglePlays = singleWinningPlays.filter(play =>
          !pairCards.has(play[0].id)
        );

        if (safeSinglePlays.length > 0) {
          const safePlay = safeSinglePlays[0]; // 最小的安全牌
          const safePower = this.calculatePlayPower(safePlay);

          // 如果安全牌和原选择牌力差距不大，选择安全牌
          if (safePower - selectedPower <= 3) {
            return safePlay;
          }
        }
      }
    }

    // 如果已经收够牌且牌力差距太大，70%概率保留大牌
    if (canBeConservative && powerGap > 8 && winningPlays.length > 1 && Math.random() > 0.3) {
      // 寻找牌力差距更小的选择
      for (let i = 1; i < winningPlays.length && i < 3; i++) {
        const altPower = this.calculatePlayPower(winningPlays[i]);
        if (altPower - currentPower <= 5) {
          return winningPlays[i];
        }
      }
    }

    // 如果需要收牌或没有更好选择，出最小能赢的牌
    return selectedPlay;
  }

  // 查找玩家所有可能的对子
  findAllPairs(player) {
    const pairs = [];
    for (let i = 0; i < player.cards.length - 1; i++) {
      for (let j = i + 1; j < player.cards.length; j++) {
        if (player.cards[i].canPairWith(player.cards[j])) {
          pairs.push([player.cards[i], player.cards[j]]);
        }
      }
    }
    return pairs;
  }

  // 检查是否可以发起扣了
  canInitiateKouLe(playerId) {
    // 必须是当前玩家的回合
    if (this.players[this.currentPlayerIndex].id !== playerId) {
      return false;
    }

    // 游戏必须在进行中
    if (this.gameStatus !== 'playing') {
      return false;
    }

    // 不能在扣了决策中
    if (this.kouLeStatus.isActive) {
      return false;
    }

    // 不能在等待收牌时
    if (this.waitingForCollection) {
      return false;
    }

    // 获取玩家对象
    const player = this.players.find(p => p.id === playerId);
    if (!player) {
      return false;
    }

    // 如果是真人玩家，只要轮到自己出牌就可以选择扣了
    if (!player.isAI) {
      return true;
    }

    // 如果是AI玩家，需要额外检查收牌数量限制
    const currentCollected = this.collectedCards[playerId] || 0;
    return currentCollected >= 9;
  }

  // 发起扣了
  initiateKouLe(playerId) {
    // 验证是否可以发起扣了
    /*if (!this.canInitiateKouLe(playerId)) {
      return { valid: false, message: '当前不能选择扣了' };
    }*/

    const initiatorPlayer = this.players.find(p => p.id === playerId);

    // 设置扣了状态
    this.kouLeStatus = {
      isActive: true,
      initiator: playerId,
      initiatorPlayer: initiatorPlayer,
      decisions: { [playerId]: 'kou' },
      xuanPlayers: [],
      riskMultiplier: 2
    };

    // 返回需要其他玩家决策
    return { valid: true, needDecision: true };
  }

  // 响应扣了决策
  respondToKouLe(playerId, decision) {
    // 验证是否在扣了决策中
    if (!this.kouLeStatus.isActive) {
      return { valid: false, message: '当前没有扣了决策' };
    }

    // 不能是发起者
    if (playerId === this.kouLeStatus.initiator) {
      return { valid: false, message: '你已经选择了扣了' };
    }

    // 不能重复决策
    if (this.kouLeStatus.decisions[playerId]) {
      return { valid: false, message: '你已经做出了选择' };
    }

    // 记录决策
    this.kouLeStatus.decisions[playerId] = decision;

    if (decision === 'xuan') {
      this.kouLeStatus.xuanPlayers.push(playerId);
      // 一旦有人选择"宣"，立即结束决策
      return this.resolveKouLe();
    }

    // 检查是否所有人都已决策
    if (Object.keys(this.kouLeStatus.decisions).length === 3) {
      return this.resolveKouLe();
    }

    return { valid: true, waiting: true };
  }

  // 解决扣了结果
  resolveKouLe() {
    const xuanCount = this.kouLeStatus.xuanPlayers.length;

    if (xuanCount === 0) {
      // 全部扣了，平局重新发牌
      return {
        valid: true,
        result: 'redeal',
        message: '所有人都选择扣了，3秒后重新发牌'
      };
    } else {
      // 有人宣，游戏继续，但保留扣了信息用于结算
      // 注意：kouLeStatus.isActive设为false，但保留其他信息
      this.kouLeStatus.isActive = false;

      // 获取选择宣的玩家名字
      const xuanPlayerNames = this.kouLeStatus.xuanPlayers.map(id => {
        const player = this.players.find(p => p.id === id);
        return player ? player.name : id;
      });

      return {
        valid: true,
        result: 'continue',
        xuanPlayers: this.kouLeStatus.xuanPlayers,
        message: `${xuanPlayerNames.join('、')}选择了宣，游戏继续`
      };
    }
  }

  // AI决策扣了
  makeAIKouLeDecision(aiPlayer) {
    // 评估手牌强度
    const handStrength = this.evaluateHandStrength(aiPlayer);

    // 当前收牌情况
    const currentCollected = this.collectedCards[aiPlayer.id] || 0;
    const remainingCards = aiPlayer.cards.length;

    // 预估能赢的轮数（基于手牌强度）
    const estimatedWinRounds = this.estimateWinningRounds(aiPlayer);

    // 预计能收到的牌数（每轮能赢的话，可以收到出牌数×3）
    // 假设平均每轮出1-2张牌
    const estimatedCardsPerRound = 1.5 * 3; // 每轮约4.5张
    const potentialCollectedCards = estimatedWinRounds * estimatedCardsPerRound;

    // 预计最终收牌总数
    const projectedTotal = currentCollected + potentialCollectedCards;

    // 调试信息
    console.log(`${aiPlayer.name} 扣了决策分析:`, {
      当前收牌: currentCollected,
      手牌强度: handStrength.toFixed(2),
      预计能赢轮数: estimatedWinRounds.toFixed(1),
      预计收牌数: potentialCollectedCards.toFixed(1),
      预计总收牌: projectedTotal.toFixed(1),
      剩余手牌: remainingCards
    });

    // 决策逻辑
    if (projectedTotal >= 9) {
      // 预计能赢（收够9张），考虑是否"宣"
      if (handStrength > 0.7) {
        // 手牌很强，有信心赢，选择"宣"
        console.log(`${aiPlayer.name} 选择宣：手牌强度高(${handStrength.toFixed(2)})，预计能收${projectedTotal.toFixed(1)}张`);
        return 'xuan';
      } else if (handStrength > 0.5 && projectedTotal >= 12) {
        // 手牌中等但预计能收很多牌，60%概率"宣"
        const willXuan = Math.random() > 0.4;
        console.log(`${aiPlayer.name} ${willXuan ? '选择宣' : '选择扣了'}：手牌中等(${handStrength.toFixed(2)})，预计能收${projectedTotal.toFixed(1)}张`);
        return willXuan ? 'xuan' : 'kou';
      } else {
        // 虽然预计能赢，但手牌不够强，保守选择"扣了"
        console.log(`${aiPlayer.name} 选择扣了：虽然预计能赢但手牌较弱(${handStrength.toFixed(2)})`);
        return 'kou';
      }
    } else {
      // 预计不能赢，必须"扣了"
      console.log(`${aiPlayer.name} 选择扣了：预计收牌不足(${projectedTotal.toFixed(1)} < 9)`);
      return 'kou';
    }
  }

  // 估算能赢的轮数
  estimateWinningRounds(player) {
    let winningRounds = 0;
    const cards = [...player.cards];
    const usedCards = new Set(); // 记录已经计算过的牌

    // 检查强力对子
    const pairs = this.findAllPairs(player);
    const strongPairs = pairs.filter(pair => {
      const power = this.calculatePlayPower(pair);
      return power >= 120; // 红相对以上
    });

    // 记录已使用的对子牌
    strongPairs.forEach(pair => {
      pair.forEach(card => usedCards.add(card.id));
    });
    winningRounds += strongPairs.length * 0.9; // 强对子90%概率能赢

    // 检查剩余的强牌（避免重复计算）
    const remainingCards = cards.filter(c => !usedCards.has(c.id));

    // 检查红尔、黑尔单张
    const erCards = remainingCards.filter(c => c.displayName.includes('尔'));
    winningRounds += erCards.length * 0.8; // 尔牌80%概率能赢

    // 检查大小王
    const jokers = remainingCards.filter(c => c.rank === 'joker');
    winningRounds += jokers.length * 0.85; // 王牌85%概率能赢

    // 检查红相、黑相单张
    const xiangCards = remainingCards.filter(c => c.displayName.includes('相') && !c.displayName.includes('尔'));
    winningRounds += xiangCards.length * 0.7; // 相牌70%概率能赢

    // 检查曲曲组合
    const ququRanks = ['J', 'Q', 'K'];
    const redQu = remainingCards.filter(c => ququRanks.includes(c.rank) && ['hearts', 'diamonds'].includes(c.suit));
    const blackQu = remainingCards.filter(c => ququRanks.includes(c.rank) && ['spades', 'clubs'].includes(c.suit));

    if (redQu.length >= 3) {
      winningRounds += 0.95; // 三张红曲曲几乎必赢
    } else if (blackQu.length >= 3) {
      winningRounds += 0.75; // 三张黑曲曲较大概率赢
    }

    // 考虑剩余手牌数量的影响
    const totalRounds = Math.ceil(cards.length / 1.5); // 预计总轮数

    // 返回预计能赢的轮数，但不超过总轮数
    return Math.min(winningRounds, totalRounds);
  }

  // 评估手牌强度 (0-1之间的值)
  evaluateHandStrength(player) {
    let strength = 0;
    const cards = player.cards;

    // 计算平均牌力
    const avgPower = cards.reduce((sum, card) => sum + card.power, 0) / cards.length;

    // 检查特殊牌
    const hasJoker = cards.some(c => c.rank === 'joker');
    const hasXiang = cards.some(c => c.displayName.includes('相'));
    const hasEr = cards.some(c => c.displayName.includes('尔'));

    // 检查对子
    const pairs = this.findAllPairs(player);
    const hasPowerfulPair = pairs.some(pair => this.calculatePlayPower(pair) >= 120);

    // 检查曲曲
    const ququCount = cards.filter(c => ['J', 'Q', 'K'].includes(c.rank)).length;

    // 综合评分
    strength = avgPower / 25; // 基础分 (最大牌力25)

    if (hasJoker) strength += 0.15;
    if (hasXiang) strength += 0.1;
    if (hasEr) strength += 0.1;
    if (hasPowerfulPair) strength += 0.15;
    if (ququCount >= 3) strength += 0.2;

    // 确保在0-1范围内
    return Math.min(1, Math.max(0, strength));
  }

  // AI是否应该发起扣了
  shouldAIInitiateKouLe(player) {
    // 检查是否可以发起扣了
    if (!this.canInitiateKouLe(player.id)) {
      return false;
    }

    // 获取当前收牌数
    const currentCollected = this.collectedCards[player.id] || 0;

    // 只有当收牌数达到9张及以上时才考虑发起扣了
    if (currentCollected < 9) {
      return false;
    }

    // 评估手牌强度
    const handStrength = this.evaluateHandStrength(player);

    // 当收牌数>=9时，无论手牌强弱都可以考虑发起扣了
    // 但手牌更强时发起扣了的收益更大

    // 收牌数>=12时，80%概率发起扣了
    if (currentCollected >= 12) {
      return Math.random() > 0.2;
    }

    // 收牌数>=9时，根据手牌强度决定
    // 手牌强度>0.7时，70%概率发起扣了
    if (handStrength > 0.7) {
      return Math.random() > 0.3;
    }

    // 手牌强度>0.5时，50%概率发起扣了
    if (handStrength > 0.5) {
      return Math.random() > 0.5;
    }

    // 手牌强度较低时，30%概率发起扣了
    return Math.random() > 0.7;
  }
}
